/*
Copyright © 2025 Zhou Yuchen <skyzyc@126.com>
*/
package cmd

import (
	"distribute-mapreduce/mrapp/plugin"
	"distribute-mapreduce/pkg/worker"
	"github.com/sirupsen/logrus"
	"os"

	"github.com/spf13/cobra"
)

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:   "distribute-mapreduce-worker",
	Short: "worker for distribute mapreduce",
	// Uncomment the following line if your bare application
	// has an action associated with it:
	Run: func(cmd *cobra.Command, args []string) {
		serverHost, err := cmd.Flags().GetString("server_host")
		if err != nil {
			logrus.Fatalf("get server host error: %v", err)
		}
		if serverHost == "" {
			logrus.Fatalf("server host is empty")
		}

		pluginFilename, err := cmd.Flags().GetString("plugin")
		if err != nil || pluginFilename == "" {
			logrus.Fatalf("get plugin filename error: %v", err)
		}
		mapFunc, reduceFunc := plugin.LoadPlugin(pluginFilename)

		resultBaseDir, err := cmd.Flags().GetString("result_base_dir")
		if err != nil {
			logrus.Fatalf("get result base dir error: %v", err)
		}

		w := worker.NewWorker(mapFunc, reduceFunc, resultBaseDir)
		err = w.Run(serverHost)
		if err != nil {
			panic(err)
		}
		logrus.Infof("worker exit")
		os.Exit(0)
	},
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	err := rootCmd.Execute()
	if err != nil {
		os.Exit(1)
	}
}

func init() {
	// Here you will define your flags and configuration settings.
	// Cobra supports persistent flags, which, if defined here,
	// will be global for your application.

	// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.distribute-mapreduce.yaml)")

	// PersistentFlags和普通的Flags在没有子命令的情况下是没有区别的。

	// Cobra also supports local flags, which will only run
	// when this action is called directly.
	rootCmd.Flags().StringP("server_host", "", "", "coordinator grpc host")
	rootCmd.Flags().StringP("plugin", "", "", "mapreduce plugin file path")
	rootCmd.Flags().StringP("result_base_dir", "", "", "mapreduce result base dir")
}
